{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "E:\\ProgramData\\Anaconda3\\lib\\site-packages\\h5py\\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n",
      "Using TensorFlow backend.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'channels_last'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "import tensorflow as tf\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "\n",
    "\n",
    "from keras.layers.core import Dense, Flatten\n",
    "from keras.layers.convolutional import Conv2D\n",
    "from keras.layers.pooling import MaxPooling2D\n",
    "\n",
    "from keras import backend as K\n",
    "\n",
    "\n",
    "K.image_data_format() "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.\n",
      "Extracting /data/train-images-idx3-ubyte.gz\n",
      "Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.\n",
      "Extracting /data/train-labels-idx1-ubyte.gz\n",
      "Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.\n",
      "Extracting /data/t10k-images-idx3-ubyte.gz\n",
      "Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.\n",
      "Extracting /data/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/data/'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "# Define loss and optimizer\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "learning_rate = tf.placeholder(tf.float32)\n",
    "\n",
    "with tf.name_scope('reshape'):\n",
    "  x_image = tf.reshape(x, [-1, 28, 28, 1])\n",
    "\n",
    "\n",
    "net = Conv2D(32, kernel_size=[5,5], strides=[1,1],activation='relu',\n",
    "                 padding='same',\n",
    "                input_shape=[28,28,1])(x_image)\n",
    "net = MaxPooling2D(pool_size=[2,2])(net)\n",
    "net = Conv2D(64, kernel_size=[5,5], strides=[1,1],activation='relu',\n",
    "                padding='same')(net)\n",
    "net = MaxPooling2D(pool_size=[2,2])(net)\n",
    "net = Flatten()(net)\n",
    "net = Dense(1000, activation='relu')(net)\n",
    "net = Dense(10,activation='softmax')(net)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.objectives import categorical_crossentropy\n",
    "cross_entropy = tf.reduce_mean(categorical_crossentropy(y_, net))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)] )\n",
    "total_loss = cross_entropy + 7e-5*l2_loss\n",
    "\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)\n",
    "\n",
    "sess = tf.Session()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "K.set_session(sess)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 100, entropy loss: 1.778901, l2_loss: 791.485840, total loss: 1.834305\n",
      "0.68\n",
      "step 200, entropy loss: 0.622114, l2_loss: 793.525391, total loss: 0.677661\n",
      "0.81\n",
      "step 300, entropy loss: 0.327506, l2_loss: 794.359924, total loss: 0.383111\n",
      "0.93\n",
      "step 400, entropy loss: 0.437858, l2_loss: 794.871643, total loss: 0.493499\n",
      "0.92\n",
      "step 500, entropy loss: 0.285049, l2_loss: 795.200500, total loss: 0.340713\n",
      "0.95\n",
      "step 600, entropy loss: 0.330835, l2_loss: 795.519226, total loss: 0.386522\n",
      "0.88\n",
      "step 700, entropy loss: 0.162768, l2_loss: 795.777832, total loss: 0.218473\n",
      "0.96\n",
      "step 800, entropy loss: 0.159416, l2_loss: 796.002380, total loss: 0.215137\n",
      "0.96\n",
      "step 900, entropy loss: 0.182345, l2_loss: 796.164307, total loss: 0.238076\n",
      "0.95\n",
      "step 1000, entropy loss: 0.119045, l2_loss: 796.337341, total loss: 0.174788\n",
      "0.98\n",
      "step 1100, entropy loss: 0.219399, l2_loss: 796.505432, total loss: 0.275154\n",
      "0.94\n",
      "step 1200, entropy loss: 0.142504, l2_loss: 796.668274, total loss: 0.198271\n",
      "0.98\n",
      "step 1300, entropy loss: 0.147293, l2_loss: 796.836670, total loss: 0.203071\n",
      "0.98\n",
      "step 1400, entropy loss: 0.228909, l2_loss: 796.978577, total loss: 0.284697\n",
      "0.95\n",
      "step 1500, entropy loss: 0.153804, l2_loss: 797.080566, total loss: 0.209600\n",
      "0.96\n",
      "step 1600, entropy loss: 0.205611, l2_loss: 797.175537, total loss: 0.261414\n",
      "0.96\n",
      "step 1700, entropy loss: 0.089849, l2_loss: 797.297913, total loss: 0.145660\n",
      "0.98\n",
      "step 1800, entropy loss: 0.193602, l2_loss: 797.401428, total loss: 0.249420\n",
      "0.95\n",
      "step 1900, entropy loss: 0.099609, l2_loss: 797.485901, total loss: 0.155433\n",
      "0.99\n",
      "step 2000, entropy loss: 0.136898, l2_loss: 797.567200, total loss: 0.192728\n",
      "0.97\n",
      "0.969\n",
      "step 2100, entropy loss: 0.055017, l2_loss: 797.632507, total loss: 0.110852\n",
      "1.0\n",
      "step 2200, entropy loss: 0.116781, l2_loss: 797.722229, total loss: 0.172622\n",
      "0.98\n",
      "step 2300, entropy loss: 0.072614, l2_loss: 797.810974, total loss: 0.128460\n",
      "1.0\n",
      "step 2400, entropy loss: 0.078838, l2_loss: 797.859070, total loss: 0.134688\n",
      "0.97\n",
      "step 2500, entropy loss: 0.057978, l2_loss: 797.925110, total loss: 0.113832\n",
      "0.99\n",
      "step 2600, entropy loss: 0.052524, l2_loss: 797.989807, total loss: 0.108384\n",
      "1.0\n",
      "step 2700, entropy loss: 0.091735, l2_loss: 798.027466, total loss: 0.147597\n",
      "0.98\n",
      "step 2800, entropy loss: 0.040619, l2_loss: 798.062317, total loss: 0.096484\n",
      "1.0\n",
      "step 2900, entropy loss: 0.133988, l2_loss: 798.107422, total loss: 0.189855\n",
      "0.98\n",
      "step 3000, entropy loss: 0.135045, l2_loss: 798.166931, total loss: 0.190917\n",
      "0.97\n",
      "0.9718\n"
     ]
    }
   ],
   "source": [
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n",
    "# Train\n",
    "for step in range(3000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  lr = 0.01\n",
    "  _, loss, l2_loss_value, total_loss_value = sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, learning_rate:lr})\n",
    "  \n",
    "  if (step+1) % 100 == 0:\n",
    "    print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    # Test trained model\n",
    "    correct_prediction = tf.equal(tf.argmax(net, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys}))\n",
    "  if (step+1) % 1000 == 0:\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
